/*
 * Copyright 2013-2019 Xia Jun(3979434@qq.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ***************************************************************************************
 *                                                                                     *
 *                        Website : http://www.farsunset.com                           *
 *                                                                                     *
 ***************************************************************************************
 */
package com.workcell.workdata.im.service.impl;

import com.workcell.workdata.im.component.event.GroupEvent;
import com.workcell.workdata.im.component.event.RobotTransferEvent;
import com.workcell.workdata.im.component.holder.UidHolder;
import com.workcell.workdata.im.component.redis.GroupMemberRedisTemplate;
import com.workcell.workdata.im.component.redis.KeyValueRedisTemplate;
import com.workcell.workdata.im.constant.MessageAction;
import com.workcell.workdata.im.entity.EventMessage;
import com.workcell.workdata.im.entity.GroupMember;
import com.workcell.workdata.im.entity.Message;
import com.workcell.workdata.im.model.request.GroupAlisaRequest;
import com.workcell.workdata.im.model.vo.GroupMemberVO;
import com.workcell.workdata.im.repository.GroupMemberRepository;
import com.workcell.workdata.im.repository.GroupMessageRepository;
import com.workcell.workdata.im.service.GroupMemberService;
import com.workcell.workdata.im.service.UserService;
import com.workcell.workdata.im.util.PageX;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;


@Service
public class GroupMemberServiceImpl implements GroupMemberService {

	private static final String NAME_REDIS_KEY = "NAME_OF_GROUP_MEMBER_%d_%d";

	@Resource
	private GroupMemberRepository groupMemberRepository;

	@Resource
	private GroupMessageRepository groupMessageRepository;

	@Resource
	private GroupMemberRedisTemplate memberRedisTemplate;

	@Resource
	private ApplicationContext applicationContext;

	@Resource
	private UserService userService;

	@Resource
	private KeyValueRedisTemplate keyValueRedisTemplate;

	@Override
	public List<GroupMemberVO> findList(long id) {
		return this.findList(Collections.singletonList(id));
	}


	@Override
	public List<GroupMemberVO> findList(List<Long> idList) {

		List<GroupMember> members = groupMemberRepository.findList(idList);

		Map<Long,String> nameMap = userService.findName(members.stream().map(GroupMember::getUid).distinct().collect(Collectors.toList()));

		Function<GroupMember, GroupMemberVO> mapper = member -> GroupMemberVO.of(member,nameMap.get(member.getUid()));

		return PageX.map(mapper,members);
	}

	@Override
	public GroupMemberVO findOne(Long id, Long uid) {
		String name = userService.findName(uid);
		GroupMember member = groupMemberRepository.findOne(id,uid);
		return GroupMemberVO.of(member,name);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void remove(long groupId) {
		groupMemberRepository.remove(groupId);
		memberRedisTemplate.remove(groupId);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void remove(GroupMember member) {
		long uid = member.getUid();
		long groupId = member.getGroupId();

		memberRedisTemplate.remove(member);

		groupMemberRepository.remove(groupId, uid);

		groupMessageRepository.deleteAll(groupId, uid,MessageAction.ACTION_3);

		/*
		 * 转让机器人给群主
		 */
		applicationContext.publishEvent(new RobotTransferEvent(groupId,Collections.singletonList(uid)));

		Message message = new EventMessage();
		message.setSender(groupId);
		message.setAction(MessageAction.ACTION_302);
		message.setContent(String.valueOf(uid));

		applicationContext.publishEvent(new GroupEvent(message,uid));

	}
 
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void remove(List<Long> idList, long groupId) {

		/*
		 *删除和他们相关的消息
		 */
		groupMessageRepository.deleteAll(groupId, idList.toArray(new Long[0]));

		memberRedisTemplate.remove(groupId,idList);

		groupMemberRepository.remove(groupId, idList);

		/*
		 * 转让机器人给群主
		 */
		applicationContext.publishEvent(new RobotTransferEvent(groupId,idList));

		long uid = UidHolder.getUid();

		Message message = new EventMessage();
		message.setAction(MessageAction.ACTION_301);
		message.setSender(groupId);

		GroupEvent event = new GroupEvent(message,uid);
		event.setUidList(idList);
		applicationContext.publishEvent(event);

		Message removeMessage = new EventMessage();
		removeMessage.setAction(MessageAction.ACTION_312);
		removeMessage.setSender(groupId);
		removeMessage.setContent(StringUtils.join(idList,","));
		GroupEvent groupEvent = new GroupEvent(removeMessage,uid);
		groupEvent.addIgnored(uid);
		applicationContext.publishEvent(groupEvent);

	}


	@Override
	@Transactional(rollbackFor = Exception.class)
	public void add(List<Long> idList, long groupId) {

		for (long uid : idList){

			GroupMember member = new GroupMember();
			member.setUid(uid);
			member.setGroupId(groupId);
			member.setType(GroupMember.TYPE_NORMAL);

			add(member);
		}

	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void add(GroupMember member) {
		member.setCreateTime(new Date());
		groupMemberRepository.saveAndFlush(member);
		memberRedisTemplate.add(member);
	}

	@Override
	public List<Long> findUidList(long id) {

		List<Long> idList = memberRedisTemplate.list(id);
		if (CollectionUtils.isEmpty(idList)){
			idList.addAll(groupMemberRepository.findUidList(id));
			memberRedisTemplate.add(id,idList);
		}
		return idList;
	}

	@Override
	public void updateType(long groupId, Long uid, byte type) {
		groupMemberRepository.updateType(groupId,uid,type);
	}

	@Override
	public void setAlias(Long uid, GroupAlisaRequest request) {
		groupMemberRepository.updateAlias(request.getGroupId(), uid, request.getAlias());

		Message message = new EventMessage();
		message.setAction(MessageAction.ACTION_318);
		message.setSender(request.getGroupId());

		GroupEvent event = new GroupEvent(message);
		event.addIgnored(uid);
		event.setReplaceable(false);
		event.setContent(uid.toString());
		event.setExtra(request.getAlias());

		applicationContext.publishEvent(event);

		keyValueRedisTemplate.delete(String.format(NAME_REDIS_KEY,request.getGroupId(),uid));

	}

	@Override
	public String findName(long groupId, long uid) {
		String key = String.format(NAME_REDIS_KEY,groupId,uid);
		String name = keyValueRedisTemplate.get(key);
		if (name != null){
			return name;
		}

		String newName;

		String alias  = groupMemberRepository.findAlias(groupId,uid);
		if (alias != null){
			newName = alias;
		}else {
			newName = userService.findName(uid);
		}

		keyValueRedisTemplate.set(key,newName, Duration.ofMinutes(10));

		return newName;
	}

}
